package com.junko.wap.interceptor;

import com.junko.core.tool.ToolWeb;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class ErrorPageHandler extends HandlerInterceptorAdapter {
    private static final Logger logger = LogManager.getLogger(ErrorPageHandler.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {
        if(modelAndView==null){
            return;
        }
        if(!ToolWeb.isAsync(request)){
            if (response.getStatus() == HttpStatus.BAD_REQUEST.value()) {
                modelAndView.setViewName("/error/400");
            } else if (response.getStatus() == HttpStatus.UNAUTHORIZED.value()) {
                modelAndView.setViewName("/error/401");
            }else if (response.getStatus() == HttpStatus.FORBIDDEN.value()) {
                modelAndView.setViewName("/error/403");
            }else if (response.getStatus() == HttpStatus.NOT_FOUND.value()) {
                modelAndView.setViewName("/error/404");
            }else if (response.getStatus() == HttpStatus.METHOD_NOT_ALLOWED.value()) {
                modelAndView.setViewName("/error/405");
            }else if (response.getStatus() == HttpStatus.INTERNAL_SERVER_ERROR.value()) {
                modelAndView.setViewName("/error/500");
            }else if (response.getStatus() == HttpStatus.BAD_GATEWAY.value()) {
                modelAndView.setViewName("/error/502");
            }
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
    }
}